﻿using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace AGage.PolarExplorer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild == null)
                openPolarInNewWindowToolStripMenuItem_Click(null, null);
            else
                openPolar((PolarForm)this.ActiveMdiChild);
        }

        private void openPolarInNewWindowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PolarForm form = new PolarForm();
            if (!openPolar(form))
                return;
            form.Plot.DisplayVMGLines = displayVMGToolStripMenuItem.Checked;
            form.Plot.DisplayVMCLines = displayVMCToolStripMenuItem.Checked;
            form.MdiParent = this;
            form.Show();
        }

        private bool openPolar(PolarForm form)
        {
            openDialog.Filter = "txt files (*.txt;*.pol;*.vpp)|*.txt;*.pol;*.vpp|csv files (*.csv)|*.csv";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                string fname = openDialog.FileName;

                try
                {
                    if (fname.EndsWith(".csv"))
                        form.Plot.Polar = new PerformancePolar(new CSVPolarProvider(fname));

                    else if (fname.EndsWith(".txt") || fname.EndsWith(".pol") || fname.EndsWith(".vpp"))
                        form.Plot.Polar = new PerformancePolar(
                                        new TextPolarProvider(File.ReadAllText(fname)));
                    else
                        MessageBox.Show("Unknown polar format", "Read Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "Read Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    form.Close();
                    return false;
                }

                // only set polar name after succesful load:
                int slash = fname.LastIndexOf('\\') + 1;
                int dot = fname.LastIndexOf('.');
                form.Text = fname.Substring(slash, dot - slash);

                return true;
            }
            return false;
        }

        private void displayVMGToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form f in this.MdiChildren)
                ((PolarForm)f).Plot.DisplayVMGLines = displayVMGToolStripMenuItem.Checked;
        }

        private void displayVMCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form f in this.MdiChildren)
                ((PolarForm)f).Plot.DisplayVMCLines = displayVMCToolStripMenuItem.Checked;
        }

        private void sameSizeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form f = this.ActiveMdiChild;
            int w = f.Width, h = f.Height;

            foreach (Form ff in this.MdiChildren)
            {
                ff.Width = w;
                ff.Height = h;
            }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop) ||
                e.Data.GetDataPresent(DataFormats.CommaSeparatedValue) ||
                e.Data.GetDataPresent(DataFormats.UnicodeText))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                DoFileDrop(e);
            else if (e.Data.GetDataPresent(DataFormats.CommaSeparatedValue))
                DoCSVDrop(e);
            else if (e.Data.GetDataPresent(DataFormats.StringFormat))
                DoTextDrop(e);
            
        }

        private void DoCSVDrop(DragEventArgs e)
        {
            object obj = e.Data.GetData(DataFormats.UnicodeText);
            string data = e.Data.GetData(DataFormats.UnicodeText).ToString();
            File.WriteAllText(@"D:\tmp\csvout.txt", data);
        }

        private void DoTextDrop(DragEventArgs e)
        {
            object obj = e.Data.GetData(DataFormats.CommaSeparatedValue);
            string data = e.Data.GetData(DataFormats.StringFormat).ToString();
            if (data.Length == 0)
                return;
            PolarForm form = new PolarForm();
            form.Text = data.Split('\n')[0].Trim();
            form.Plot.DisplayVMGLines = displayVMGToolStripMenuItem.Checked;
            form.Plot.DisplayVMCLines = displayVMCToolStripMenuItem.Checked;
            form.MdiParent = this;
            if (data.Contains(",") || data.Contains(";"))
            {
                form.Plot.Polar = new PerformancePolar(
                    CSVPolarProvider.FromStringData(data));
                form.Text = "CSV Drop";
            }
            else
                form.Plot.Polar = new PerformancePolar(
                                new TextPolarProvider(data));
            form.Show();
        }

        delegate void HandleDrop(Array a);

        private void DoFileDrop(DragEventArgs e)
        {
            try
            {
                Array a = (Array)e.Data.GetData(DataFormats.FileDrop);
                if (a != null)
                {
                    // Call OpenFiles asynchronously.
                    // Explorer instance from which file is dropped is not respondin
                    this.BeginInvoke(new HandleDrop(OpenFiles), new Object[] { a });
                    this.Activate();        // in the case Explorer overlaps this form
                }
            }
            catch (Exception)
            { }
        }

        private void OpenFiles(Array fileNames)
        {
            for (int i = 0; i < fileNames.Length; ++i)
            {
                PolarForm form = new PolarForm();
                string sFile = fileNames.GetValue(i).ToString();
                int slash = sFile.LastIndexOf('\\') + 1;
                int dot = sFile.LastIndexOf('.');
                form.Text = sFile.Substring(slash, dot - slash);
                form.Plot.DisplayVMGLines = displayVMGToolStripMenuItem.Checked;
                form.Plot.DisplayVMCLines = displayVMCToolStripMenuItem.Checked;
                form.MdiParent = this;
                if (sFile.EndsWith(".csv"))
                    form.Plot.Polar = new PerformancePolar(new CSVPolarProvider(sFile));
                else
                    form.Plot.Polar = new PerformancePolar(
                                    new TextPolarProvider(File.ReadAllText(sFile)));
                form.Show();
            }
        }

        private void cSVToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            string data = Clipboard.GetData(DataFormats.StringFormat).ToString();
            if (data.Trim().Length < 100)
                return;
            PolarForm form = new PolarForm();
            form.Plot.DisplayVMGLines = displayVMGToolStripMenuItem.Checked;
            form.Plot.DisplayVMCLines = displayVMCToolStripMenuItem.Checked;
            form.MdiParent = this;
            form.Plot.Polar = new PerformancePolar(CSVPolarProvider.FromStringData(data));
            form.Text = "CSV Paste";            
            form.Show();
        }

        private void textToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            string data = Clipboard.GetData(DataFormats.StringFormat).ToString();
            if (data.Trim().Length < 100)
                return;
            PolarForm form = new PolarForm();
            form.Text = data.Split('\n')[0].Trim();
            form.Plot.DisplayVMGLines = displayVMGToolStripMenuItem.Checked;
            form.Plot.DisplayVMCLines = displayVMCToolStripMenuItem.Checked;
            form.MdiParent = this;
            form.Plot.Polar = new PerformancePolar(new TextPolarProvider(data));
            form.Show();
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.FileName = "iexplore";
            proc.StartInfo.Arguments = "http://solpolarexplorer.codeplex.com/documentation";
            proc.Start();
        }
    }
}

/*
private void outputSplinedToolStripMenuItem_Click(object sender, EventArgs e)
{
    StringBuilder buf = new StringBuilder();
    PerformancePolar polar = ((PolarForm)this.ActiveMdiChild).Plot.Polar;
    string name = ((PolarForm)this.ActiveMdiChild).Text;

    buf.AppendLine("<vpp><Name>").Append(name).Append("</Name>");
    buf.AppendLine("<tws_splined>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39</tws_splined>");
    buf.Append("<twa_splined>");
    for (int i = 0; i <= 180; ++i)
    {
        buf.Append(i);
        if (i < 180)
            buf.Append(' ');
    }
    buf.AppendLine("</twa_splined>");
    buf.Append("<bs_splined>");
    double KNT_MS = 1.94384449;
    for (int tws = 1; tws < 40; ++tws)
    {
        for (int twa = 0; twa <= 180; ++twa)
        {
            buf.Append(polar[twa, tws / KNT_MS]);
            if (twa < 180)
                buf.Append(' ');
        }
        buf.Append(';');
    }
    buf.AppendLine("</bs_splined></vpp>");

    if (!Directory.Exists("C:\\SOLPolars"))
        Directory.CreateDirectory("C:\\SOLPolars");

    File.WriteAllText(@"C:\SOLPolars\" + name + ".xml", buf.ToString());

    // Now as CSV:
    buf = new StringBuilder();
    buf.AppendLine("\"TWS[m/s]\",\"TWS[kt]\",\"TWA\",\"SPD[kt]\"");
    for (int tws = 0; tws < 40; ++tws)  // in m/s
    {
        for (int twa = 0; twa <= 180; ++twa)
        {
            buf.AppendFormat("{0},{1},{2},{3}", tws, tws * KNT_MS, twa, polar[twa, tws*KNT_MS]);
            buf.AppendLine();
        }
    }
    File.WriteAllText(@"C:\SOLPolars\" + name + ".csv", buf.ToString());
}
*/